<?php


namespace app\api\model;

use app\lib\exception\ProductException;

class Product extends  BaseModel
{
    protected $hidden = ['delete_time','main_img_id','pivot','from','category_id','create_time','update_time'];

    public  function  getMainImgUrlAttr($value,$data){
        return $this->prefixImgUrl($value,$data);
    }

    public function imgs(){
        return $this->hasMany('ProductImage','product_id','id');
    }

    public  static  function  getMostRecent($count){
        $products = self::limit($count)->order('create_time desc')->select();
        if ($products->isEmpty()){
            throw new  ProductException();
        }
        // 数据集返回类型
//        'resultset_type'  => 'collection',
//        $collection = collection($products);
        $products = $products->hidden(['summary']);
        return $products;
    }

    public static function  getProductsByCategoryID($categoryID){
        $products = self::where('category_id','=',$categoryID)->select();
        if ($products->isEmpty()){
            throw new ProductException();
        }
        $products = $products->hidden(['summary']);
        return $products;
    }
    public static  function  getProductByID($id){
//        $product = self::with('imgs.img')->find($id);
        $product = self::with([
            'imgs' => function($query){
            $query->with(['img'])->order('order','asc');
            }
        ])->find($id);

        if (!$product){
            throw new  ProductException();
        }
        return $product;
    }





























}